<template>
  <div>
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 按钮添加分类 @click="getCater"-->
      <el-button type="primary" @click="getCater">添加分类</el-button>
      <vxe-table border ref="tableRef" :column-config="{ resizable: true }" :tree-config="{}" :data="tableData">
        <vxe-column type="seq" width="180" title="序号" tree-node></vxe-column>
        <vxe-column field="cat_name" title="分类名字" ></vxe-column>
        <vxe-column field="cat_deleted" title="是否有效">
          <template v-slot="scope">
            <el-icon v-if="!scope.row.cat_deleted">
              <CircleCheck color="green" />
            </el-icon>
            <el-icon v-else>
              <CircleClose color="red" />
            </el-icon>
          </template>
        </vxe-column>
        <vxe-column field="cat_level" title="排序">
          <template v-slot="scope">
            <el-tag v-if="scope.row.cat_level === 0" size="large">一级</el-tag>
            <el-tag v-if="scope.row.cat_level === 1" size="large" type="success">二级</el-tag>
            <el-tag v-if="scope.row.cat_level === 2" size="large" type="warning">三级</el-tag>
          </template>
        </vxe-column>
        <vxe-column title="操作">
          <template v-slot="scope">
            <!-- 修改 -->
            <el-button type="primary" :icon="EditPen" size="large" @click="getCateRow(scope.row)"></el-button>
            <!-- 删除 -->
            <el-button type="danger" :icon="Delete" size="large" @click="delCate(scope.row.cat_id)"></el-button>
          </template>
        </vxe-column>
      </vxe-table>
      <!-- 分页 
        v-model:current-page当前页数  v-model:page-size每页显示条目个数
        small是否使用小型分页样式  disabled是否禁用分页-->
      <el-pagination
        v-model:current-page="page.currentPage"
        v-model:page-size="page.pageSize"
        :page-sizes="[10, 20, 30, 40]"
        small
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 添加分类 -->
    <el-dialog title="添加分类" v-model="dialogVisible" width="50%" @close="resetUser">
      <el-form ref="addform1" :model="addform" :rules="addformRule" label-width="100px">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addform.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader
            style="width: 100%"
            v-model="addform.cat_pid"
            :options="options"
            :props="props"
            clearble
          ></el-cascader>
        </el-form-item>
      </el-form>
      <!-- <span slot="footer" class="dialog-footer"> -->
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="addCategories">确 定</el-button>
      <!-- </span> -->
    </el-dialog>
    <!-- 修改对话框 -->
    <el-dialog title="修改分类" v-model="dialogVisibleUpdate" width="50%">
      <el-form ref="updateform" :model="addform" :rules="addformRule" label-width="100px">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addform.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <el-button @click="dialogVisibleUp">取 消</el-button>
      <el-button type="primary" @click="updateCategories">确 定</el-button>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { CircleCheck, CircleClose, EditPen, Delete } from '@element-plus/icons-vue'
import { ref, onMounted } from 'vue'
import request from '@/util/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import { VxeTableInstance } from 'vxe-table'

// 控制添加分类的显示
const dialogVisible = ref(false)
// 添加的表单信息
const addform = ref({
  cat_pid: [],
  cat_name: '',
  cat_level: 0,
})
const addform1 = ref({})
const addform2 = ref({
  cat_pid: [],
  cat_name: '',
  cat_level: 0,
})
const resetUser = () => {
  Object.assign(addform.value, addform2.value)
}
const addformRule = {
  cat_name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
}
// 级联数据
const options = ref([])
const props = {
  label: 'cat_name',
  value: 'cat_id',
  checkStrictly: true,
  expandTrigger: 'hover',
}
//  分页
// 总条数
const total = ref(100)
const page = ref({
  // 当前页
  currentPage: 1,
  // 每页查询条数
  pageSize: 10,
})
// 是否禁用分页
const disabled = ref(false)
// 是否为分页按钮添加背景色
const background = ref(false)
// page-size 改变时触发
const handleSizeChange = (Size: any) => {
  page.value.pageSize = Size
  getCategorieslist()
  console.log('handleSizeChange')
}
// current-page 改变时触发
const handleCurrentChange = (Current: any) => {
  page.value.currentPage = Current
  getCategorieslist()
  console.log('handleCurrentChange')
}

interface RowVO {
  id: number
  parentId: number | null
  name: string
  type: string
  size: number
  date: string
}

const tableRef = ref<VxeTableInstance<RowVO>>()

const tableData = ref<RowVO[]>([
  { id: 10000, parentId: null, name: 'Test1', type: 'mp3', size: 1024, date: '2020-08-01' },
  { id: 10050, parentId: null, name: 'Test2', type: 'mp4', size: 0, date: '2021-04-01' },
  { id: 24300, parentId: 10050, name: 'Test3', type: 'avi', size: 1024, date: '2020-03-01' },
  { id: 20045, parentId: 24300, name: 'Test4', type: 'html', size: 600, date: '2021-04-01' },
  { id: 10053, parentId: 24300, name: 'Test5', type: 'avi', size: 0, date: '2021-04-01' },
  { id: 24330, parentId: 10053, name: 'Test6', type: 'txt', size: 25, date: '2021-10-01' },
  { id: 21011, parentId: 10053, name: 'Test7', type: 'pdf', size: 512, date: '2020-01-01' },
  { id: 22200, parentId: 10053, name: 'Test8', type: 'js', size: 1024, date: '2021-06-01' },
  { id: 23666, parentId: null, name: 'Test9', type: 'xlsx', size: 2048, date: '2020-11-01' },
  { id: 23677, parentId: 23666, name: 'Test10', type: 'js', size: 1024, date: '2021-06-01' },
  { id: 23671, parentId: 23677, name: 'Test11', type: 'js', size: 1024, date: '2021-06-01' },
  { id: 23672, parentId: 23677, name: 'Test12', type: 'js', size: 1024, date: '2021-06-01' },
  { id: 23688, parentId: 23666, name: 'Test13', type: 'js', size: 1024, date: '2021-06-01' },
  { id: 23681, parentId: 23688, name: 'Test14', type: 'js', size: 1024, date: '2021-06-01' },
  { id: 23682, parentId: 23688, name: 'Test15', type: 'js', size: 1024, date: '2021-06-01' },
  { id: 24555, parentId: null, name: 'Test16', type: 'avi', size: 224, date: '2020-10-01' },
  { id: 24566, parentId: 24555, name: 'Test17', type: 'js', size: 1024, date: '2021-06-01' },
  { id: 24577, parentId: 24555, name: 'Test18', type: 'js', size: 1024, date: '2021-06-01' },
])
onMounted(() => {
  getCategorieslist()
})
const getCategorieslist = async () => {
  const { data, meta }: any = await request({
    url: 'categories',
    method: 'GET',
    params: {
      pagenum: page.value.currentPage,
      pagesize: page.value.pageSize,
    },
  })
  if (meta.status !== 200) {
    return ElMessage.error('获取失败')
  }
  tableData.value = data.result
  console.log(tableData)
  total.value = data.total
}
// 根据类型获取级联数据
const getCater = async () => {
  dialogVisible.value = true
  const { data, meta } = await request({
    url: '/categories',
    method: 'GET',
    params: {
      type: 2,
    },
  })
  if (meta.status !== 200) {
    return ElMessage.error('获取父级分类失败')
  }
  options.value = data
  console.log(data)
}
// 添加确定按钮
const addCategories = async () => {
  addform1.value.validate(async (valid) => {
    // 没有通过校验
    if (!valid) {
      return ElMessage.error('请填写正确数据')
    }
    const lenght = addform.value.cat_pid.length
    // 0 1级 1 2级 2 三级
    addform.value.cat_level = lenght
    if (lenght !== 0) {
      addform.value.cat_pid = addform.value.cat_pid[lenght - 1]
    } else {
      addform.value.cat_pid = 0
    }
    // console.log(this.addform);
    const { meta } = await request({
      url: '/categories',
      method: 'POST',
      data: addform.value,
    })
    if (meta.status !== 201) {
      return ElMessage.error('添加分类失败')
    }
    ElMessage.success('添加成功')
    dialogVisible.value = false
    getCategorieslist()
  })
}
// 修改对话框是否显示
const dialogVisibleUpdate = ref(false)
// 获取分类数据
const getCateRow = (row) => {
  // 给表单赋值
  addform.value = row
  // 显示对话框
  dialogVisibleUpdate.value = true
}
// 修改取消按钮
const dialogVisibleUp = () => {
  dialogVisibleUpdate.value = false
  addform.value.cat_name = ''
}
// 修改框确定按钮   提交更新数据
const updateCategories = async () => {
  const { meta } = await request({
    url: `categories/${addform.value.cat_id}`,
    method: 'PUT',
    data: addform.value,
  })
  if (meta.status !== 200) {
    return ElMessage.error('更新失败')
  }
  dialogVisibleUpdate.value = false
  ElMessage.success('更新成功')
  addform.value.cat_name = ''
  // 刷新页面
  getCategorieslist()
}
// 根据id删除分类
const delCate = async (id) => {
  try {
    await ElMessageBox.confirm('此操作将会永久删除该文件,是否继续？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error',
    })
    const { meta }: any = await request({
      url: `categories/${id}`,
      method: 'delete',
    })
    if (meta.status !== 200) {
      return ElMessage.error('删除失败')
    }
    ElMessage.success('删除成功')
    // 重新渲染页面
    getCategorieslist()
  } catch (error) {
    return ElMessage.info('已经取消')
  }
}
</script>

<style scoped></style>
